package com.talent.jiwen_teacher.my;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.liveaa.livemeeting.sdk.biz.core.ABCLiveSDK;
import com.liveaa.livemeeting.sdk.util.GetPathFromUri4kitkat;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.SelfIntroductionResult;
import com.talent.jiwen_teacher.http.result.VideoResult;
import com.talent.jiwen_teacher.ui.widgets.LoadDialog;
import com.talent.jiwen_teacher.ui.widgets.NoEmojiEditText;
import com.talent.jiwen_teacher.util.ImageUtil;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.models.sort.SortingTypes;
import droidninja.filepicker.utils.Orientation;
import rx.Observable;


/**
 * Created by qyqx on 2018/8/17.
 * 风采展示
 */

public class StyleShowActivity extends BaseActivity {

    @BindView(R.id.videoplayer)
    JZVideoPlayerStandard videoplayer;

    @BindView(R.id.up_video)
    Button up_video;

    @BindView(R.id.videoStatusTv)
    TextView videoStatusTv;

    @BindView(R.id.img_take)//占位图
            ImageView img_take;

    @BindView(R.id.edit_introduce)//个人简介
            NoEmojiEditText edit_introduce;


    String videoUrl;
    String itroduceStr;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_style_show;
    }

    @Override
    public String titleName() {
        return "风采展示";
    }

    @Override
    protected void initData() {
        getSelfIntroduction();
    }


    private void initVideo(String url) {
        if (Validators.isEmpty(url)) {
            videoplayer.setVisibility(View.GONE);
            img_take.setVisibility(View.VISIBLE);
            videoStatusTv.setVisibility(View.VISIBLE);
            videoStatusTv.setText("暂无影音，请上传");
        } else {
            videoplayer.setVisibility(View.VISIBLE);
            img_take.setVisibility(View.GONE);
            videoplayer.setUp(url, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
            if (!url.endsWith(".mp3") && !url.endsWith(".aac") && !url.endsWith(".amr") && !url.endsWith(".wav") && !url.endsWith(".m4a")) {
                videoplayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                setVideoCover(url);
            } else {
                videoplayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
            }

        }
    }

    private ArrayList<String> filePaths = new ArrayList<>();
    private static final int CUSTOM_REQUEST_CODE = 532;

    @OnClick({R.id.up_video})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.up_video:
//                if(Validators.isEmpty(getSystem())){
//                    FilePickerBuilder.getInstance().setMaxCount(1)
//                            .setSelectedFiles(filePaths)
//                            .setActivityTitle("选择视频")
//                            .setActivityTheme(R.style.LibAppTheme)
//                            .enableVideoPicker(true)
//                            .showFolderView(false)
//                            .enableSelectAll(false)
//                            .enableImagePicker(false)
//                            .pickPhoto(this, CUSTOM_REQUEST_CODE);
//                }else{
//                    if (getSystem().equals(SYS_FLYME)) {
////                    ImageUtil.pickVideo(StyleShowActivity.this, 1, pathList, false);
//                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                        intent.setType("video/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
//                        intent.addCategory(Intent.CATEGORY_OPENABLE);
//                        startActivityForResult(intent, 1);
//                    } else {
//                        FilePickerBuilder.getInstance().setMaxCount(1)
//                                .setSelectedFiles(filePaths)
//                                .setActivityTitle("选择视频")
//                                .setActivityTheme(R.style.LibAppTheme)
//                                .enableVideoPicker(true)
//                                .showFolderView(false)
//                                .enableSelectAll(false)
//                                .enableImagePicker(false)
//                                .pickPhoto(this, CUSTOM_REQUEST_CODE);
//                    }
//                }
//                Intent intent2 = new Intent(this, VideoPickActivity.class);
//                intent2.putExtra(IS_NEED_CAMERA, true);
//                intent2.putExtra(Constant.MAX_NUMBER, 1);
//                intent2.putExtra(IS_NEED_FOLDER_LIST, true);
//                startActivityForResult(intent2, Constant.REQUEST_CODE_PICK_VIDEO);
                itroduceStr = edit_introduce.getText().toString();
                showOutDialog();
                break;
        }
    }


    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }


    /**
     * 选择资料
     */
    AlertView alertView;

    protected void showOutDialog() {

        if (alertView != null && alertView.isShowing()) {
            alertView.dismiss();
        }

        if (alertView == null) {
            alertView = new AlertView("上传影音", null, "取消", null,
                    new String[]{"上传视频", "上传音频", "保存个人介绍"},
                    this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    switch (position) {
                        case 0:
                            FilePickerBuilder.getInstance().setMaxCount(1)
                                    .setSelectedFiles(filePaths)
                                    .setActivityTitle("选择视频")
                                    .setActivityTheme(R.style.LibAppTheme)
                                    .enableVideoPicker(true)
                                    .showFolderView(false)
                                    .enableSelectAll(false)
                                    .enableImagePicker(false)
                                    .pickPhoto(StyleShowActivity.this, CUSTOM_REQUEST_CODE);
                            break;
                        case 1:
                            onPickVoice();
                            break;
                        case 2:
                            if (Validators.isEmpty(itroduceStr)) {
                                showToast("请先填写个人介绍");
                            } else {
                                upVideo(videoUrl);
                            }

                            break;
                    }
                }
            });
            alertView.setCancelable(true).show();
        } else if (alertView != null) {
            alertView.show();
        }
    }


    public void onPickVoice() {
        filePaths.clear();
        String[] pdfs = {".mp3", ".aac", ".amr", ".wav", ".m4a"};
        int maxCount = 1;
        FilePickerBuilder.getInstance()
                .setMaxCount(maxCount)
                .setSelectedFiles(filePaths)
                .setActivityTheme(R.style.LibAppTheme)
                .setActivityTitle("选择音频")
                .addFileSupport("请选择您要上传的音频文件", pdfs)
                .enableDocSupport(false)
                .enableSelectAll(true)
                .sortDocumentsBy(SortingTypes.name)
                .withOrientation(Orientation.UNSPECIFIED)
                .pickFile(StyleShowActivity.this);
    }


    private void uploadFile(File file) {

        ImageUtil.upLoadSingleImg(file.getAbsolutePath(), new ImageUtil.ImgUpLoadListener() {
            @Override
            public void OnSuccess(String successUrl) {
                videoUrl = successUrl;
                upVideo(videoUrl);
            }

            @Override
            public void OnError(String message) {
                LoadDialog.dismiss(StyleShowActivity.this);
                showToast(message);
            }

            @Override
            public void OnListUpSuccess(List<String> successFileList) {
            }
        });


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK && data != null) {//是否选择，没选择就不会继续
                    Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor actualimagecursor = getContentResolver().query(uri, proj, null, null, null);
//            Cursor actualimagecursor = getContentResolver().query(uri,null,null,null,null);
                    if (actualimagecursor != null) {
                        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        if (actualimagecursor.moveToFirst()) {
                            String img_path = actualimagecursor.getString(actual_image_column_index);
//                    Log.e("aaa", "onActivityResult: ==="+ actualimagecursor.getString(1)+"=="+ actualimagecursor.getString(2)+"==="+actualimagecursor.getString(3)+"==="+actualimagecursor.getString(4));
                            actualimagecursor.close();
                            if (!Validators.isEmpty(img_path)) {
                                File file = new File(img_path);
                                if (file.length() > 100 * 1024 * 1024) {
                                    showToast("请选择小于100M的视频");
                                } else {
                                    LoadDialog.show(StyleShowActivity.this);
                                    uploadFile(file);
                                }
                            } else {
                                showToast("选取失败，请重新选择。");
                            }
                        } else {
                            showToast("选取失败，请重新选择。");
                        }

                    } else {
                        showToast("选取失败，请重新选择。");
                    }
                }

                break;
            case CUSTOM_REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    filePaths.clear();
                    filePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
                    if (filePaths.size() > 0) {
                        String img_path = filePaths.get(0);
                        if (!Validators.isEmpty(img_path)) {
                            File file = new File(img_path);
                            if (file.length() > 100 * 1024 * 1024) {
                                showToast("请选择小于100M的视频");
                            } else {
                                LoadDialog.show(StyleShowActivity.this);
                                uploadFile(file);
                            }
                        } else {
                            showToast("选取失败，请重新选择。");
                        }

                    } else {
                        showToast("选取失败，请重新选择。");
                    }
                }
                break;

            case FilePickerConst.REQUEST_CODE_DOC:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    filePaths.clear();
                    filePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_DOCS));
                    if (filePaths.size() > 0) {
                        String name = filePaths.get(0);
                        Uri uri = Uri.fromFile(new File(name));
                        if (uri != null) {
                            final String filename = GetPathFromUri4kitkat.getPath(this, uri);
                            File file = new File(filename);
                            if (file != null && file.exists()) {
                                final String filePath = file.getAbsolutePath();// ".mp3",".aac",".amr",".wav",".m4a"
                                if (filePath.endsWith(".mp3") || filePath.endsWith(".aac") ||
                                        filePath.endsWith(".amr") || filePath.endsWith(".wav") ||
                                        filePath.endsWith(".m4a")) {
                                    LoadDialog.show(StyleShowActivity.this);
                                    uploadFile(file);
                                } else {
                                    ABCLiveSDK.showToast("只能上传音频文件");
                                }
                            } else {
                                ABCLiveSDK.showToast("文件不能为空");
                            }
                        }
                    }
                }
                break;

        }
    }


    Bitmap bitmap;

    private void setVideoCover(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever retr = new MediaMetadataRetriever();
                retr.setDataSource(url, new HashMap<String, String>());
                bitmap = retr.getFrameAtTime();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bitmap != null) {
                            videoplayer.thumbImageView.setImageBitmap(bitmap);
                        } else {
                            videoplayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                        }
                    }
                });
            }
        }).start();
    }


    public static String getStr(String str) {
        return Validators.isEmpty(str) ? "" : str;
    }


    private void upVideo(final String videoUrl) {

        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.getUserId());
        map.put("videoUrl", getStr(videoUrl));
        map.put("userProfile", getStr(itroduceStr));
        Observable observable = ApiFactory.getEducationApiSingleton().uploadSelfIntroduction(SPUtil.getToken(), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<VideoResult>(this) {
            @Override
            protected void _onNext(VideoResult videoResult) {
                if (videoResult != null) {
                    SPUtil.stringIn(SPConstant.VIDEO_URL, videoResult.videoUrl);
                    initVideo(videoUrl);
                    videoStatusTv.setVisibility(View.VISIBLE);
                    videoStatusTv.setText("等待审核");
                }
                LoadDialog.dismiss(StyleShowActivity.this);
                showToast("上传成功,请等待审核");
            }

            @Override
            protected void _onError(String message) {
                LoadDialog.dismiss(StyleShowActivity.this);
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }


    private void getSelfIntroduction() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().getSelfIntroduction(SPUtil.getToken(), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SelfIntroductionResult>(StyleShowActivity.this) {
            @Override
            protected void _onNext(SelfIntroductionResult selfIntroductionResult) {
                videoUrl = selfIntroductionResult.getUserVideo();
                itroduceStr = selfIntroductionResult.getUserProfile();
                if (!Validators.isEmpty(itroduceStr)) {
                    edit_introduce.setText(itroduceStr);
                }
                initVideo(videoUrl);
                switch (selfIntroductionResult.getVideoExamineStatus()) {
                    case 0:
                        videoStatusTv.setVisibility(View.VISIBLE);
                        videoStatusTv.setText("等待审核");
                        break;
                    case 1:
                        videoStatusTv.setVisibility(View.VISIBLE);
                        videoStatusTv.setText("审核已通过");
                        break;
                    case 2:
                        videoStatusTv.setVisibility(View.VISIBLE);
                        if (Validators.isEmpty(selfIntroductionResult.getErrorMessage())) {
                            videoStatusTv.setText("审核未通过");
                        } else {
                            videoStatusTv.setText("审核未通过：" + selfIntroductionResult.getErrorMessage());
                        }
                        break;
//                    case 9:
//                        videoStatusTv.setVisibility(View.GONE);
//                        break;
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    public static final String SYS_EMUI = "sys_emui";
    public static final String SYS_MIUI = "sys_miui";
    public static final String SYS_FLYME = "sys_flyme";
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
    private static final String KEY_EMUI_API_LEVEL = "ro.build.hw_emui_api_level";
    private static final String KEY_EMUI_VERSION = "ro.build.version.emui";
    private static final String KEY_EMUI_CONFIG_HW_SYS_VERSION = "ro.confg.hw_systemversion";

    public static String getSystem() {
        String SYS = null;
        try {
            Properties prop = new Properties();
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            if (prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                    || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                    || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null) {
                SYS = SYS_MIUI;//小米
            } else if (prop.getProperty(KEY_EMUI_API_LEVEL, null) != null
                    || prop.getProperty(KEY_EMUI_VERSION, null) != null
                    || prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, null) != null) {
                SYS = SYS_EMUI;//华为
            } else if (getMeizuFlymeOSFlag().toLowerCase().contains("flyme")) {
                SYS = SYS_FLYME;//魅族
            }
            ;
        } catch (IOException e) {
            e.printStackTrace();
            return SYS;
        }
        return SYS;
    }

    public static String getMeizuFlymeOSFlag() {
        return getSystemProperty("ro.build.display.id", "");
    }

    private static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("get", String.class, String.class);
            return (String) get.invoke(clz, key, defaultValue);
        } catch (Exception e) {
        }
        return defaultValue;
    }


}
